import os
import shutil
from pathlib import Path
from util_slash import f_win, f_unix


def exists(root, folder_list):
    for folder in folder_list:
        if f_unix(root).startswith(f_unix(folder)):
            return True
    return False


def copy_torrent_files(source_dir, target_dir):
    """
    扫描指定目录中的所有.torrent文件并复制到目标目录

    参数:
        source_dir (str): 要扫描的源目录路径
        target_dir (str): 目标目录路径
    """
    # 确保目标目录存在
    Path(target_dir).mkdir(parents=True, exist_ok=True)

    # 计数器
    copied_count = 0

    try:
        # 使用os.walk递归遍历源目录及其所有子目录
        for root, dirs, files in os.walk(source_dir):
            if exists(root, ignore_folder_list):
                continue
            for file in files:
                # 检查文件是否为.torrent文件
                if file.lower().endswith('.torrent'):
                    # 构建完整的源文件路径
                    source_file = os.path.join(root, file)

                    # 构建目标文件路径
                    target_file = os.path.join(target_dir, file)

                    try:
                        # 复制文件到目标目录（使用copy2保留元数据）
                        shutil.copy2(source_file, target_file)
                        print(f"已复制: {source_file} -> {target_file}")
                        copied_count += 1

                    except Exception as e:
                        print(f"复制文件 {source_file} 时出错: {e}")

    except Exception as e:
        print(f"遍历目录 {source_dir} 时出错: {e}")

    print(f"\n复制完成！共复制 {copied_count} 个.torrent文件")


if __name__ == "__main__":
    base_path = r"E:\torrents_collector"
    torrent_dict = {
        # r'\\diskstation3\10T_01\Fitgirl': "games_fitgirl_tmp",
        # r'\\diskstation3\10T_02\Fitgirl': "games_fitgirl",
        # r'\\diskstation3\14T_02': "games_fitgirl_tmp",
        # r'\\diskstation\Cartoons&Docs': "cartoons",
        # r'\\diskstation\Movies': "movies",
        # r'\\diskstation\oTVs\07.Movies_managed': "movies",
        # r'\\diskstation\TVs\07.Movies_managed': "movies",
        # r'\\diskstation\TVs\07.TVs_managed': "tvs",
        # r'\\diskstation\TVs\07.TVs_unmanaged': "tvs",
        # r'\\diskstation\oTVs\07.oTVs_managed': "otvs",
        # r'\\diskstation\oTVs\07.oTVs_unmanaged': "otvs",
        r"E:/": "e",
    }
    ignore_folder_list = [
        r'E:/torrents_collector',
        r'E:/fitgirl_repack_torrents',
        r'E:/btbbt_data_torrent',
    ]

    for k, v in torrent_dict.items():
        # 设置源目录和目标目录
        source_directory = k
        target_directory = os.path.join(base_path, v)
        if not os.path.isdir(target_directory) and os.path.dirname(target_directory) != "":
            os.makedirs(target_directory)
        # 验证源目录是否存在
        if not os.path.exists(source_directory):
            print(f"错误: 源目录 '{source_directory}' 不存在")
        else:
            # 执行复制操作
            copy_torrent_files(source_directory, target_directory)